<template>
  <div class="app-page">
    <el-table-form ref="form" :model="query">
      <el-form-item label="单据类型:" prop="billType">
        <el-select v-model="query.billType" filterable clearable placeholder="请选择">
          <el-option
            v-for="item in billTypeMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item class="merge-item">
        <el-select v-model="conditionType" style="width: 170px; margin-right: 2px;">
          <el-option label="单据号" value="billCode" />
          <el-option label="退款申请单号" value="refundBillCode" />
          <el-option label="交易订单号" value="outTradeNo" />
          <el-option label="第三方支付流水号" value="transactionId" />
          <el-option label="客户名称" value="csmName" />
        </el-select>
        <el-input v-model.trim="conditionText" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item :table-form-merge="2" class="merge-item">
        <el-select v-model="dateType" style="width: 170px; margin-right: 2px;">
          <el-option label="申请时间" value="hap" />
          <el-option label="执行退款时间" value="createTime" />
        </el-select>
        <el-date-picker
          v-model="date"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          unlink-panels
          :clearable="false"
          :default-time="['00:00:00', '23:59:59']"
        />
      </el-form-item>
      <el-form-item label="支付渠道:" prop="paymentChannel">
        <el-select v-model="query.paymentChannel" filterable clearable placeholder="请选择">
          <el-option
            v-for="item in paymentChannelMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="支付方式:" prop="payType">
        <el-select v-model="query.payType" filterable clearable placeholder="请选择">
          <el-option
            v-for="item in payTypeMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属机构:">
        <el-tree-select
          v-model="query.orgId"
          :clearable="true"
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
          }"
          :tree-params=" {
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props:{
              value:'orgId',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData
          }"
          @node-click="selectTreeChange"
          @select-clear="clearOrg"
        />
      </el-form-item>
      <el-form-item :table-form-merge="0.2">
        <el-checkbox v-model="isIncludeSub" label="包含下级" />
      </el-form-item>
      <el-form-item class="merge-item" label="操作人:">
        <el-input v-model="query.operator" placeholder="请输入" clearable />
      </el-form-item>
      <template v-slot:btns>
        <el-button v-permission="[90102, 1]" type="primary" icon="el-icon-search" @click="search">查询</el-button>
      </template>
    </el-table-form>
    <div style="margin-bottom: 10px;" class="btn-group">
      <el-button-group>
        <el-button v-permission="[90102, 2]" type="primary" icon="el-icon-download" :loading="$loadingPlugin.exportFile" @click="exportFile">导出</el-button>
      </el-button-group>
    </div>
    <lb-table
      ref="lbTable"
      v-loading="$loadingPlugin.fetchData"
      v-el-height-adaptive-table="{bottomOffset:10}"
      border
      element-loading-text="加载中"
      :column="tableData.column"
      :data="tableData.data"
      highlight-current-row
      pagination
      :total="tableData.total"
      custom-column
      @fetch="fetchData"
    >
      <template slot="tips">
        退款金额：{{ tableData.tag }}
      </template>
    </lb-table>
    <detail ref="detail" />
  </div>
</template>

<script>
  import { queryRefundTransactionFlowList, queryExportRefundTransactionFlowList, queryExportDomain, queryMap, queryCorpAndCrmOrg } from '@/api'
  import moment from 'dayjs'
  import { formatColumnMap, parseTime } from '@/utils'
  import { mapGetters } from 'vuex'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import getTreeData from '@/utils/jsonTree'
  import Detail from './components/Detail'
  import { refundChannelMap } from '@/utils/map'

  export default {
    name: 'refundTransactions',
    components: {
      Detail
    },
    data() {
      return {
        exportDomain: '',
        treeData: [],
        billTypeMap: [],
        conditionType: 'billCode',
        conditionText: '',
        date: [moment().startOf('day'), moment().endOf('day')],
        paymentChannelMap: [],
        payTypeMap: [],
        isIncludeSub: false, // 是否包含下级
        query: {
          billType: '',
          paymentChannel: '',
          payType: ''
        },
        searchParams: {},
        tableData: {
          tag: 0,
          data: [],
          column: [
            {
              type: 'index',
              fixed: 'left'
            },
            {
              prop: 'refundBillCode',
              width: 200,
              fixed: 'left',
              label: '退款申请单号'
            },
            {
              prop: 'billType',
              fixed: 'left',
              label: '单据类型',
              render: (h, { row }) => <span>{ row.billType && formatColumnMap(this.billTypeMap, 'value', row.billType, 'desc') }</span>
            },
            {
              prop: 'billCode',
              align: 'left',
              label: '单据号'
            },
            {
              prop: 'goodsCount',
              align: 'left',
              label: '总数量'
            },
            {
              prop: 'goodsDesc',
              align: 'left',
              width: 170,
              label: '商品描述'
            },
            {
              prop: 'billTotalFee',
              align: 'right',
              label: '单据金额'
            },
            {
              prop: 'refundFee',
              width: 120,
              align: 'right',
              label: '申请退款金额'
            },
            {
              prop: 'refundChannel',
              width: 120,
              label: '退款渠道',
              render: (h, { row }) => <span>{ (row.refundChannel || row.refundChannel === 0) && refundChannelMap[row.refundChannel] }</span>
            },
            {
              prop: 'createTime',
              label: '执行退款时间',
              width: 180,
              render: (h, { row }) => <span>{ row.createTime && parseTime(row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
            },
            {
              prop: 'reqDt',
              label: '申请时间',
              width: 180,
              render: (h, { row }) => <span>{ row.reqDt && parseTime(row.reqDt, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
            },
            {
              prop: 'orgName',
              width: 170,
              label: '所属机构'
            },
            {
              prop: 'operator',
              label: '操作人'
            },
            {
              prop: 'auditor',
              label: '审核人'
            },
            {
              prop: 'payType',
              label: '支付方式',
              render: (h, { row }) => <span>{ row.payType && formatColumnMap(this.payTypeMap, 'value', row.payType, 'desc') }</span>
            },
            {
              prop: 'paymentChannel',
              width: 120,
              label: '支付渠道',
              render: (h, { row }) => <span>{ row.paymentChannel && formatColumnMap(this.paymentChannelMap, 'value', row.paymentChannel, 'desc') }</span>
            },
            {
              prop: 'csmName',
              label: '客户名称'
            },
            {
              prop: 'csmPhone',
              width: 120,
              label: '客户电话'
            },
            {
              prop: 'csmAddress',
              width: 200,
              label: '客户地址'
            },
            {
              prop: 'transactionId',
              label: '第三方支付流水号',
              width: 300
            },
            {
              prop: 'outTradeNo',
              label: '交易订单号',
              width: 300
            }
          ]
        },
        dateType: 'hap'
      }
    },
    computed: {
      ...mapGetters([
        'orgList',
        'userInfo'
      ])
    },
    async created() {
      await Promise.all([this.getExportDomain(), this.getTreeData(), this.queryOptionsMap()])
    },
    methods: {
      // 获取导出域名
      getExportDomain() {
        mergeAsyncFunc(queryExportDomain)
          .then((res) => {
            this.exportDomain = res.data
          })
      },
      // 获取所属机构数据
      async getTreeData() {
        const res1 = await queryCorpAndCrmOrg({ containCrmOrgflag: 1, corpSN: this.userInfo.corpSN })
        this.treeData = getTreeData(res1.data)
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      async fetchData({ currentPage, pageSize }) {
        const query = {
          ...this._getQuery(this.query),
          currentPage,
          pageSize,
          orgId: this.isIncludeSub ? 0 : this.query.orgId,
          orgSNNo: this.isIncludeSub ? this.query.orgSNNo : undefined
        }
        if (this.date && this.date.length > 0) {
          if (this.dateType === 'hap') {
            query.hapStart = this.date[0]
            query.hapEnd = this.date[1]
          } else if (this.dateType === 'createTime') {
            query.createTime = this.date[0]
            query.createTimeEnd = this.date[1]
          }
        }
        query[this.nameType] = this.nameText
        query[this.conditionType] = this.conditionText
        if (!this.query.billType) query.billType = -1
        const diff = moment(this.date[1]).diff(moment(this.date[0]), 'days')
        if (diff > 366) {
          this.$message.error('申请时间最大支持查询1年')
          return
        }
        const res = await queryRefundTransactionFlowList(query)
        this.searchParams = query
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
        this.tableData.tag = res.data.tag
      },
      // 查询枚举
      async queryOptionsMap() {
        const [res1, res2, res3] = await Promise.all([queryMap({ enumName: 'Payment_BillType' }), queryMap({ enumName: 'PayAccountType' }), queryMap({ enumName: 'PaymentChannel' })])
        this.billTypeMap = res1.data // 单据类型
        this.payTypeMap = res2.data // 支付方式
        this.paymentChannelMap = res3.data // 支付渠道
      },
      async openDetail(row) {
        await this.$refs.detail.open(row)
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 导出
      async exportFile() {
        const _this = this
        this.$confirm(`确定导出数据？`, '提示', {
          type: 'warning'
        }).then(() => {
          const copyColumn = JSON.parse(JSON.stringify(this.tableData.column))
          const str = {}
          copyColumn.forEach(item => {
            str[item.prop] = item.label
          })
          queryExportRefundTransactionFlowList({
            paramInfo: _this._getQuery(this.searchParams),
            kv: str // 表格列
          }).then((res) => {
            window.open(`${this.exportDomain}/page/export/frame?key=${res.data}`, '_blank')
          })
        })
      },
      reset() {
        this.dateType = 'hap'
        this.date = []
        this.personType = 'createUserId'
        this.personId = ''
        this.query = {
          stockCode: '',
          inStoreId: '',
          truckId: '',
          carrierCode: '',
          stockStatus: ''
        }
        this.$refs.form.resetFields()
      },
      // 选择所属机构
      async selectTreeChange(value) {
        console.log('selectTreeChange', value)
        this.query.orgSNNo = value.orgSNNo
      },

      clearOrg() {
        this.query.orgId = ''
        this.query.orgSNNo = ''
      }
    }
  }
</script>

<style lang="scss" scoped>
.svg-row {
  text-align: center;
  .svg-container {
    display: inline-block;
    width: 25px;
    cursor: pointer;
    .transfer-icon {
      width: 25px;
      height: 25px;
      vertical-align: middle;
    }
  }
}
.el-form-item .el-form-item {
  margin-bottom: 0;
}
.btn-group {
  display: flex;
  justify-content: space-between;
}
</style>
